package mybatis.plugin;

import java.util.List;

import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.JavaTypeResolver;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.Interface;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import org.mybatis.generator.internal.types.JavaTypeResolverDefaultImpl;

public class MapperPlugin extends PluginAdapter {

	public boolean validate(List<String> warnings) {
		return true;
	}

	/**
	 * 生成dao
	 */
	@Override
	public boolean clientGenerated(Interface interfaze, TopLevelClass topLevelClass,
			IntrospectedTable introspectedTable) {  	
	    /*
    	JavaTypeResolver javaTypeResolver = new JavaTypeResolverDefaultImpl();

    	List<IntrospectedColumn> cloun = introspectedTable.getPrimaryKeyColumns();
    	if(CollectionUtils.isEmpty(cloun)) {
    		System.out.println(introspectedTable.getRemarks());
    		System.out.println(introspectedTable.getFullyQualifiedTable().getIntrospectedTableName());
    	}
    	
    	FullyQualifiedJavaType calculateJavaType = javaTypeResolver
                 .calculateJavaType(cloun.get(0));
        FullyQualifiedJavaType fqjt = new FullyQualifiedJavaType("BaseMapper<" + introspectedTable.getBaseRecordType()
                + "," + introspectedTable.getExampleType() +","+ calculateJavaType.getShortName()+">");
		*/
		
		FullyQualifiedJavaType fqjt;
		if (introspectedTable.getRules().generatePrimaryKeyClass()) {
			fqjt = new FullyQualifiedJavaType("BaseMapper<" + introspectedTable.getBaseRecordType() + ","
					+ introspectedTable.getExampleType() + "," + introspectedTable.getPrimaryKeyType() + ">");
		} else {
			if (introspectedTable.getPrimaryKeyColumns().isEmpty()) {
				return false;
			}
			JavaTypeResolver javaTypeResolver = new JavaTypeResolverDefaultImpl();
			FullyQualifiedJavaType calculateJavaType = javaTypeResolver
					.calculateJavaType(introspectedTable.getPrimaryKeyColumns().get(0));
			fqjt = new FullyQualifiedJavaType("BaseMapper<" + introspectedTable.getBaseRecordType() + ","
					+ introspectedTable.getExampleType() + "," + calculateJavaType.getShortName() + ">");
		}
		String targetPackage = this.context.getJavaClientGeneratorConfiguration().getTargetPackage();
		//targetPackage = targetPackage.substring(0, targetPackage.lastIndexOf('.'));
		FullyQualifiedJavaType imp = new FullyQualifiedJavaType(targetPackage + ".base.BaseMapper");// baseMapper包名
		/**
		 * 添加 extends BaseMapper
		 */
		interfaze.addSuperInterface(fqjt);

		/**
		 * 添加import BaseMapper;
		 */
		interfaze.addImportedType(imp);
		/**
		 * 方法不需要
		 */
		interfaze.getMethods().clear();
		interfaze.getAnnotations().clear();
		return true;
	}
}
